import Dialog from '../../../assets/vant/dialog/dialog';
const util = require('../../../utils/util.js');
var storage = require('../../../utils/storage.js')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    intro: '',
    coverImg:'',
    coverfileList:[],
    imagefileList:[],//批量上传图片微信临时地址
    imagefileIds: [],// 批量上传图片objectid
    videofileList:'',
    fileName:'',
    defaultOption:{
      id: '0',
      name: '图片'
    },
    options: [{
      city_id: '0',
      city_name: '图片'
    },{
      city_id: '1',
      city_name: '视频'
    }, {
      city_id: '3',
      city_name: '音频'
    }, {
      city_id: '2',
      city_name: '文字'
    }],
    currentType:0,
    userInfo:null,
    activityId: null,
    status: false,
    hiddenName: false,
    hiddenInput: true,
    min: 0,
    max: 5000,
    max02: 8000,
    content:'',
    cover: '',
    coverObjectid: '',
    username: "",
    phone: "",
    width: "",
    height: ""

  },
  
  selectchange:function(e){
    console.log(e.detail.id);
    if(e.detail.id == 2){
      this.setData({
        hiddenName: true,
        hiddenInput:false,
      })
    } else {
      this.setData({
        hiddenName:false,
        hiddenInput:true
      })
    }
  

    this.setData({
      currentType: e.detail.id,
      imagefileList:[],
      fileName:'',
      content:'',
      currentWordNumber: 0,
      currentWordNumber02: 0
    })
  },
  
  // 封面
  deleteImgcover: function (e) {
    var _index = e.detail.index;
    this.data.coverfileList.splice(_index, 1);
    this.setData({
      coverfileList: this.data.coverfileList,
      coverImg: ""
    })
  },
  afterUploadcover: function (e) {
    console.log(e);
    wx.showLoading({
      title: '上传中',
    })
    var that = this;/*  */
    var imgurl = e.detail.file.path; //获取上传图片的临时地址
    // 把图片上传到服务器,并在页面中显示封面
    wx.uploadFile({
      url: 'https://wxgt.chaoxing.com/wechat/upload',
      filePath: imgurl,
      name: 'file',
      // header: {
      //   "Content-Type": "multipart/form-data"
      // },
      success(res) {
        console.log(res.data);
        var data = JSON.parse(res.data);
        console.log(data.imgUrl);
        var imgObj = {
          url: data.imgUrl
        }
        that.data.coverfileList.push(imgObj)
        that.setData({
          coverfileList: that.data.coverfileList,
          coverImg: data.imgUrl,
          width: data.width,
          height: data.height,
          coverObjectid: data.objectid
        })
        wx.hideLoading();
      },
      fail: function(){
        wx.hideLoading();
      }
    });
    
  },
  // 图片作品
  imagedeleteImg: function (e) {
    var _index = e.detail.index;
    this.data.imagefileList.splice(_index, 1);
    this.data.imagefileIds.splice(_index,1);
    this.setData({
      imagefileList: this.data.imagefileList,
      imagefileIds: this.data.imagefileIds
    })
  },
  imageafterUpload:function(e){
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    var files = e.detail.file; //获取上传图片的临时地址
    console.log(e);
    var filePaths = [];
    var filePathUrls = [];
    for(var i =0;i < files.length;i++){
      var temp = { 'url': files[i].path};
      filePaths[i] = temp;
      filePathUrls[i] = files[i].path;
    }
    console.log(filePaths);
    that.setData({
      imagefileList: that.data.imagefileList.concat(filePaths)
    })

    var promise = Promise.all(filePathUrls.map((tempFilePath, index) => {
      return new Promise(function (resolve, reject) {
        wx.uploadFile({
          url: 'https://wxgt.chaoxing.com/wechat/uploadfiles',
          filePath: tempFilePath,
          name: 'file',
          // header: {
          //   "Content-Type": "multipart/form-data"
          // },
          formData: {},
          success: function (res) {
            that.data.imagefileIds.push(res.data)
            that.setData({
              imagefileIds: that.data.imagefileIds
            })
          },
          fail: function (err) {
            console.log(err);
            wx.hideLoading();
          }
        });
      });
    }));
    wx.hideLoading()
    promise.then(function (results) {
      console.log(results); //返回上传成功的数据
      wx.hideLoading()
    }).catch(function (err) {
      console.log(err);
      wx.hideLoading()
    });
  },

  /**
   * 判断上传类型为音频或者视频
   */
  uploadType: function(e){
    var that = this;
    var type = this.data.currentType;
    if(type == 1){
      this.chooseVideo();
    }else if(type == 2){
      //文档类型，需要隐藏掉作品描述
    }else if(type == 0){
      //图片类型，需要显示作品描述
      
    }else if(type == 3){
      this.setData({
        currentType: 3
      })
      //将作品名称和封面保存到缓存一小时
      storage.put('resu_type',3, 3600);
      storage.put('title', this.data.title, 3600);
      storage.put('coverImg', this.data.coverImg, 3600);
      storage.put('username', this.data.username, 3600);
      storage.put('userMobile', this.data.phone, 3600);
      storage.put('coverObjectid', this.data.coverObjectid, 3600);
      storage.put('height', this.data.height, 3600);
      storage.put('width', this.data.width, 3600);
      storage.put('productionType', this.data.currentType, 3600);
      // storage.put('intro', this.data.intro, 3600);
      //跳转到录制音频页面
      wx.navigateTo({
        url: '/pages/readingAloud/readingAloud?activityId=' + that.data.activityId + "&cover=" + that.data.cover,
      })
      //this.chooseAudio();
    }
  },

  // 视频上传
  chooseVideo: function () {
    console.log("---1")
    var that = this;
    wx.chooseVideo({
      count: 1,
      sizeType: ['original', 'compressed'],
      //album 从相册选视频，camera 使用相机拍摄，默认为：['album', 'camera']
      sourceType: ['album', 'camera'],
      //拍摄视频最长拍摄时间，单位秒。最长支持60秒
      maxDuration: 60,
      //前置或者后置摄像头，默认为前后都有，即：['front', 'back']
      camera: ['front', 'back'],
      success: function (res) {
        that.uploadvideo(res.tempFilePath);
      }
    })
  },
  //上传视频 目前后台限制最大100M，以后如果视频太大可以在选择视频的时候进行压缩
  uploadvideo: function (src) {
    wx.showLoading({
      title: '上传中...',
    })
    var that = this;
    that.setData({
      imagefileIds: [],
      fileName: ""
    })
    console.log(src)
    wx.uploadFile({
      url: 'https://wxgt.chaoxing.com/wechat/uploadfile',//服务器接口
      filePath: src,
      // header: {
      //   'content-type': 'multipart/form-data'
      // },
      name: 'file',//服务器定义的Key值
      success: function (res) {
        console.log(res.data);
        var data = JSON.parse(res.data);
        if(data.code == 200){
          console.log('上传成功');
          that.data.imagefileIds.push(data.data.objectid)
          
          that.setData({
            imagefileIds: that.data.imagefileIds,
            fileName: data.data.fileName
          })
          wx.hideLoading();
        }else{
          console.log('接口调用失败');
          wx.hideLoading();
        }
        
      },
      fail: function () {
        console.log('接口调用失败')
        wx.hideLoading();
      }
    })
  },

  //选择音频
  chooseAudio: function () {
    var that = this
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success(res) {
        console.log(res)
        console.log(res.tempFiles[0].path);
        //TODO 需要判断下音频的格式

        that.uploadvideo(res.tempFiles[0].path);
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //屏蔽右上角分享功能
    wx.hideShareMenu();
    console.log(options);
    var activityId = options.activityId;
    var cover = options.cover;
    var user = wx.getStorageSync('userInfo');
    var phone = wx.getStorageSync('phone');
    user['phone'] = phone
    this.setData({
      userInfo:user,
      username: user.nickName,
      phone: phone,
      activityId: activityId,
      cover: cover
    })
    //音频上传完后跳转到表单提交页面，需要初始化参数
    var resu_type = storage.get("resu_type");
    if(resu_type != undefined && resu_type ==3){
      var title = storage.get("title");
      var coverImg = storage.get("coverImg");
      var username = storage.get("username");
      var phone = storage.get("userMobile");
      var coverObjectid = storage.get("coverObjectid");
      var height = storage.get("height");
      var width = storage.get("width");
      var currentType = storage.get("productionType");
      var intro = storage.get("content");
      console.log("content: " + intro);
      var audio_objectid = storage.get("audio_objectid");
      var temp = storage.get("temp");
      var imgObj = {
        url: coverImg
      }
      this.data.coverfileList.push(imgObj);
      this.data.imagefileIds.push(audio_objectid);
      var defaultOption = {
        'id': '3',
        'name': '音频'}
      this.setData({
        fileName: temp,
        title:title,
        coverImg:coverImg,
        username: username,
        phone: phone,
        coverObjectid: coverObjectid,
        height: height,
        width: width,
        currentType: currentType,
        intro: intro,
        coverfileList: this.data.coverfileList,
        imagefileIds: this.data.imagefileIds,
        defaultOption: defaultOption
      })
    }

    

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function (e) {
    console.log("卸载");
    var resu_type = storage.get("resu_type");
    console.log("缓存中类型： " + resu_type);
    if(resu_type != undefined && resu_type == 3){
      storage.remove('resu_type');
      storage.remove("coverImg");
      storage.remove("title");
      storage.remove("content");
      storage.remove("username");
      storage.remove("userMobile");
      storage.remove("coverObjectid");
      storage.remove("height");
      storage.remove("width");
      storage.remove("productionType");
      storage.remove("audio_objectid");
      storage.remove("temp");
      storage.remove("productionDescription");
      
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 监听作品名称输入
   */
  changeinpt: function (e) {
    this.setData({
      title: e.detail.value
    })
  },

  /**
   * 简介输入
   */
  introInput: function(e){
    console.log(e);
    this.setData({
      intro: e.detail.value
    })
    var value = e.detail.value;
    var len = parseInt(value.length);
    if (len > this.data.max02) return;
    this.setData({
      currentWordNumber02: len
    });
    if(this.data.currentWordNumber02 == 5000){
      wx.showModal({
        title: '提示',
        content: '您输入的次数已达上限',
      })
    }
  },
    /**
   * 文字限制
   */
  inputs: function (e) {
    console.log(e);
    this.setData({
      intro: e.detail.value
    })
    var value = e.detail.value;
    var len = parseInt(value.length);
    if (len > this.data.max) return;
    this.setData({
      currentWordNumber: len
    });
    if(this.data.currentWordNumber == 5000){
      wx.showModal({
        title: '提示',
        content: '您输入的次数已达上限',
      })
    }
  },

  /**
   * 提交
   *//*  */
  formSubmit: function (e) {
    this.setData({
      status: true
    })
    var that = this;
    var activityId =  that.data.activityId;//活动ID
    var productionTitle = that.data.title == undefined ? "" : that.data.title ;//作品名称
    var fid = app.globalData.fid;//单位fid
    var uid = wx.getStorageSync('cxid');//用户uid
    var username = that.data.userInfo.nickName;//姓名
    var userMobile = that.data.userInfo.phone;//手机号
    var productionCover = that.data.coverImg;//作品封面
    var coverObjectid = that.data.coverObjectid;//封面的objectid
    var height = that.data.height;//作品高度
    var width = that.data.width;//封面宽度
    var productionType = that.data.currentType;//作品类型
    var productionDescription = that.data.intro;//作品简介
    var ids = that.data.imagefileIds.join(',');//图片资源支持多个，视频音频限制为1个， 暂定objectid,objectid
    var avatarUrl = wx.getStorageSync('userInfo').avatarUrl;
    console.log("地址： " + avatarUrl);
    //判断必填参数
    if(activityId ==undefined || activityId == null){
      wx.showToast({
        title: '请检查活动是否存在',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        status: false
      })
    }else if(productionTitle == undefined || productionTitle.replace(/\s+/g, '') == ''){
      wx.showToast({
        title: '请检查作品名称是否填写',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        status: false
      })
    }else if(fid == undefined || fid == null){
      wx.showToast({
        title: '单位属性失效',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        status: false
      })
    }else if(uid == undefined || uid == null){
      wx.showToast({
        title: '登录状态已失效',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        status: false
      })
    }else if(username == undefined || username.replace(/\s+/g, '') == ''){
      wx.showToast({
        title: '请检查姓名是否填写',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        status: false
      })
    }else if(userMobile == undefined || userMobile.replace(/\s+/g, '') == ''){
      wx.showToast({
        title: '请检查手机号是否填写',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        status: false
      })
    }else if(productionCover == undefined || productionCover == ''){
      wx.showToast({
        title: '请检查封面是否上传',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        status: false
      })
    }else if(coverObjectid == undefined || coverObjectid == ''){
      wx.showToast({
        title: '封面标识缺失',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        status: false
      })
    }else if(height == undefined || height == ''){
      wx.showToast({
        title: '封面高度尺寸缺失',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        status: false
      })
    }else if(width == undefined || width == ''){
      wx.showToast({
        title: '封面宽度尺寸缺失',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        status: false
      })
    }else if(productionType == undefined || productionType == null){
      wx.showToast({
        title: '请检查作品类型是否选择',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        status: false
      })
    }else if(productionDescription == undefined || productionDescription.replace(/\s+/g, '') == ''){
      wx.showToast({
        title: '请检查作品简介是否填写',
        icon: 'none',
        duration: 1500
      })
      this.setData({
        status: false
      })
    }else{
      //参数正常，执行上传操作
      wx.showLoading({
        title: '正在提交',
      })
      var ids = this.data.imagefileIds.join(',');
      console.log(ids);
      var that = this;
      wx.request({
        url: app.globalData.activityHost + '/services/activityaction/doUploadProduct',
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        data: {
          activityId: that.data.activityId,//活动ID
          productionTitle: that.data.title,//作品名称
          fid: app.globalData.fid,//单位fid
          uid: wx.getStorageSync('cxid'),//用户uid
          username: that.data.username,//姓名
          userMobile: that.data.phone,//手机号
          productionCover: that.data.coverImg,//作品封面
          coverObjectid: that.data.coverObjectid,//封面的objectid
          height: that.data.height,//作品高度
          width: that.data.width,//封面宽度
          productionType: that.data.currentType,//作品类型
          productionDescription: encodeURIComponent(that.data.intro),//作品简介
          
          avatarUrl: avatarUrl, //微信头像
          resu: ids //图片资源支持多个，视频音频限制为1个， 暂定objectid,objectid
        },
        success: function(res){
          console.log(res);
          if(res.data.result == "0"){
            //清除缓存中的信息
            storage.remove("coverImg");
            storage.remove("title");
            storage.remove("content");
            storage.remove("username");
            storage.remove("userMobile");
            storage.remove("coverObjectid");
            storage.remove("height");
            storage.remove("width");
            storage.remove("productionType");
            storage.remove("audio_objectid");
            storage.remove("temp");
            storage.remove("resu_type");
            //跳转
            wx.hideLoading()
            // wx.redirectTo({
            //   url: '/pages/productionDetail/productionDetail?activityId=' + that.data.activityId,
            // })
            var delta = productionType == 3 ? 3 : 1;
            wx.navigateBack({
              delta: delta
            })
          }else{
            console.log(res.data.msg);
            that.setData({
              status: false
            })
            wx.hideLoading()
          }
          //成功后页面跳转
  
        },
        fail: function(){
          wx.hideLoading()
          console.log("上传异常")
          that.setData({
            status: false
          })
        }
      })
    }

    
    
  },

  /**
   * 绑定修改真实姓名
   */
  editName: function(e){
    console.log(e);
    this.setData({
      username: e.detail.value
    })
  },

  /**
   * 绑定手机号
   */
  editPhone: function(e){
    console.log(e);
    this.setData({
      phone: e.detail.value
    })
  }

})